import DatePicker from "components/antd-compatible/date-picker";
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Switch, Form, Button, message, } from 'antd';
import { messages } from 'share/common';
import moment from 'moment'
import Priority from 'components/template/priority/priority';
import auditBasisService from 'containers/finance-setting/audit-basis-config/audit-basis-service';
import { permission } from '../../permisson';
import Condition from 'components/condition'
import 'styles/finance-setting/audit-basis-config/book-date-setting.scss';

const { If } = Condition;

@connect(mapStateToProps)
@permission
class NewAuditBasisConfig extends Component {

  static PropTypes = {};

  handleRenderView = value => {
    let temp = value.split(',');
    return temp.map(item => <div style={{ whiteSpace: 'normal' }}>{item}</div>)
  };

  state = {
    formList: {
      enabled: {
        name: messages('common.column.status')/*状态*/,
        component: Switch,
        initData: true,
        valuePropName: 'checked'
      },
      levelOrgId: {
        name: messages('expense-14.key307')/*所属组织*/,
        component: Priority,
        require: true,
        filterValue: value => {return { rangeValue: {
          setOfBooksId: value,
          setOfBooksName: this.props.record.levelOrgName
        }}},
        params: {
          top: "SET_OF_BOOK",
          showCompany: false,
          onlySetOfBooks: true
        }
      },
      startDate: {
        name: messages('expense-14.key308')/*开始时间*/,
        component: DatePicker,
        require: true,
        filterValue: value => moment(value),
        params: {
          getCalendarContainer: () => document.getElementsByClassName('book-date-setting-detail')[0],
          showTime: { defaultValue: moment('00:00', 'HH:mm') },
          format: 'YYYY-MM-DD HH:mm'
        }
      },
      endDate: {
        name: messages('expense-14.key309')/*结束时间*/,
        component: DatePicker,
        require: true,
        filterValue: value => moment(value),
        params: {
          getCalendarContainer: () => document.getElementsByClassName('book-date-setting-detail')[0],
          showTime: { defaultValue: moment('23:59', 'HH:mm') },
          format: 'YYYY-MM-DD HH:mm'
        }
      },
      bookDate: {
        name: messages('expense-14.key292')/*记账日期*/,
        component: DatePicker,
        require: true,
        filterValue: value => moment(value),
      }
    },
    submitLoading: false
  };

  componentDidMount() {
    this.handleInit();
  }

  handleInit = () => {
    let { formList } = this.state;
    const { record } = this.props;
    Object.keys(formList)
      .map(key => {
        let filterValue = formList[key].filterValue;
        if (record[key] !== null && record[key] !== void 0) {
          formList[key].initData = filterValue ? filterValue(record[key]) : record[key];
        }
      });
    this.setState({ formList });
  };

  handleSubmit = e => {
    e.preventDefault();
    const { record, record: { bookDateConfigId } } = this.props;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        let params = values;
        params.levelCode = 'SET_OF_BOOK';
        if (bookDateConfigId) {
          params.bookDateConfigId = bookDateConfigId;
          params.levelOrgId = record.levelOrgId;
        } else {
          params.levelOrgId && params.levelOrgId.rangeValue && (params.levelOrgId = params.levelOrgId.rangeValue.id);
        }
        this.setState({ submitLoading: true });
        auditBasisService.saveBookDate(params)
          .then(() => {
            message.success(messages('common.save.success',{arg1: ''})/*{arg1} 保存成功*/);
            this.props.close(true);
          })
          .finally(() => {
            this.setState({ submitLoading: false });
          });
      }
    });
  };

  handleCancel = () => {
    this.props.close(false);
  };

  renderForm = () => {
    const { formList, submitLoading } = this.state;
    const { form: { getFieldDecorator }, record: { readOnly, bookDateConfigId } } = this.props;
    const formItemLayout = { labelCol: { span: 7 }, wrapperCol: { span: 15, offset: 1 } };
    const formArray = Object.keys(formList)
      .map(key => {
        const middleForm = formList[key];
        let { name, child, params = {}, require, component, extra } = middleForm;
        params.disabled = readOnly || this.isReadOnly();
        key === 'levelOrgId' && (params.disabled = params.disabled || !!bookDateConfigId);
        const Element = React.createElement(component, params, child);
        return (
          <Form.Item  {...formItemLayout} extra={extra} label={name}>
            {getFieldDecorator(key, {
              rules: [{
                required: !!require,
                message: messages('common.select')/*请选择*/
              }],
              initialValue: formList[key].initData,
              valuePropName: formList[key].valuePropName || 'value'
            })(Element)}
          </Form.Item>
        );
      });
    return (
      <Form className='new-form book-date-setting-detail' onSubmit={this.handleSubmit}>
        {
          formArray
        }
        <div className="slide-footer">
          <If value={!(readOnly || this.isReadOnly())}>
            <Button type="primary" htmlType="submit" loading={submitLoading}>{messages('common.save')/*保存*/}</Button>
          </If>
          <Button onClick={this.handleCancel}>{messages('common.cancel')/*取消*/}</Button>
        </div>
      </Form>
    );

  };

  render() {
    return (
      <div className="book-date-setting-detail">
        {this.renderForm()}
      </div>
    );
  }
}


function mapStateToProps(state) {
  return {
    currentMenuPermission: state.main.currentMenuPermission,
  };
}

const WrappedNewAuditBasisConfig = Form.create()(NewAuditBasisConfig);

export default WrappedNewAuditBasisConfig;
